package cn.com.open.itembank.sqlprovider;

import cn.com.open.itembank.common.enums.SysState;
import cn.com.open.itembank.dto.RulesSearchModel;
import cn.com.open.itembank.utils.StringUtil;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * The type Rules read sql provider.
 */
public class RulesSqlProvider {

    /**
     * 根据条件获取策略列表分页信息sql
     * <p>
     * itemBankId    课程题库ID
     * pageNum       每页条数
     * pageSize      每页条数
     * sortOrder     排序类型
     * sortName      排序字段
     * orgid         机构ID
     * ruleName      策略名称
     *
     * @param parameter the parameter
     * @return the rules query
     */
    public String getRulesQuery(Map<String, Object> parameter) {

        RulesSearchModel dto = (RulesSearchModel) parameter.get("RulesModel");
        String itemBankId = dto.getItembankId();
        Integer pageSize = dto.getPageSize();
        Integer pageNumber = dto.getPageNumber();
        String orgid = dto.getOrgId();
        String sortName = dto.getSortName();
        String ruleName = dto.getRuleName();
        String sortOrder = dto.getSortOrder();

        StringBuilder sbSql = new StringBuilder();

        sbSql.append(String.format(" SELECT TOP %d * FROM", pageSize));
        sbSql.append(String.format(" (SELECT ROW_NUMBER() OVER(ORDER BY a.%s %s) AS RN,a.* FROM", sortName, sortOrder));
        sbSql.append(String.format(" (SELECT * from Rules where Status <> %d", SysState.DELETE.getIndex()));
        if (!StringUtils.isEmpty(orgid)) {
            sbSql.append(String.format(" AND OrganizationID = '%s'", orgid));
        }
        sbSql.append(String.format(" AND CourseID = '%s') a ) AS DATALIST WHERE RN > %d", itemBankId,(pageNumber - 1) * pageSize));
        if (!StringUtil.isEmpty(ruleName)) {
            sbSql.append(String.format(" AND RuleName LIKE '%%%s%%'", ruleName));
        }

        return sbSql.toString();
    }

    /**
     * 根据条件获取策略列表总条数sql.
     *
     * @param parameter the parameter
     * @return the rules count
     */
    public String getRulesCount(Map<String, Object> parameter) {

        RulesSearchModel dto = (RulesSearchModel) parameter.get("RulesModel");
        String itemBankId = dto.getItembankId();
        String orgid = dto.getOrgId();
        String ruleName = dto.getRuleName();

        StringBuilder sbSql = new StringBuilder();
        sbSql.append(String.format(" SELECT count(1) FROM Rules WHERE CourseID  = '%s'", itemBankId));
        if (!StringUtils.isEmpty(orgid)) {
            sbSql.append(String.format(" AND OrganizationID = '%s'", orgid));
        }
        sbSql.append(String.format(" AND Status <> %d", SysState.DELETE.getIndex()));
        if (StringUtil.isEmpty(ruleName)) {
            sbSql.append(String.format(" AND RuleName LIKE '%%%s%%'", ruleName));
        }

        return sbSql.toString();
    }
}
